package com.zqf;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompFrameHandler;
import org.springframework.messaging.simp.stomp.StompHeaders;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.messaging.simp.stomp.StompSessionHandler;
import org.springframework.messaging.simp.stomp.StompSessionHandlerAdapter;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.springframework.web.socket.sockjs.client.RestTemplateXhrTransport;
import org.springframework.web.socket.sockjs.client.SockJsClient;
import org.springframework.web.socket.sockjs.client.Transport;
import org.springframework.web.socket.sockjs.client.WebSocketTransport;

import com.google.common.collect.Maps;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApiGatewayApp.class)
public class WebSocketDemo {
	
	
	 
	 
	 @SuppressWarnings("unchecked")
	@Test
	 public void SockJsClient1() {
		 
		
		 
		 
	        final CountDownLatch latch = new CountDownLatch(1);  
	        RestTemplate rest = new RestTemplate();
	        List<Transport> transports = new ArrayList<>(1);  
	        transports.add(new RestTemplateXhrTransport(rest));  
	        transports.add(new WebSocketTransport(new StandardWebSocketClient()));  
	        WebSocketClient transport = new SockJsClient(transports);  
	        WebSocketStompClient stompClient = new WebSocketStompClient(transport);  
	  
	        stompClient.setMessageConverter(new MappingJackson2MessageConverter());  
	        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();  
	        taskScheduler.afterPropertiesSet();  
	        stompClient.setTaskScheduler(taskScheduler); // for heartbeats  
	        Map<String,Object> request = Maps.newHashMap();
	        request.put("username", "admin");
	        request.put("rememberMe", true);
	        request.put("password",  "483922");
//	        request.put("password",  "admin");
	        Map<String,Object> map = rest.postForObject("https://www.shanfupai.com/api/authenticate", request, Map.class);
	        String jwt = (String) map.get("id_token");
	       
	        String url = "wss://www.shanfupai.com/sockjs/websocket/tracker?access_token="+jwt;  
	        System.err.println(url);
	        StompSessionHandler myHandler = new MyStompSessionHandler(latch);  
	        stompClient.connect(url, myHandler);  
	        try {  
//	            latch.await(3, TimeUnit.SECONDS);  
	        	 latch.await();  
	        }  
	        catch (InterruptedException e) {  
	            // TODO Auto-generated catch block  
	            e.printStackTrace();  
	        }  
	 }
	
	 
		@SuppressWarnings("unchecked")
		@Test
		 public void Client1() {
			 
			
			 
			 
		        final CountDownLatch latch = new CountDownLatch(1);  
		        RestTemplate rest = new RestTemplate();
  
		        WebSocketClient webSocketClient = new StandardWebSocketClient();
		        
		        WebSocketStompClient stompClient = new WebSocketStompClient(webSocketClient);
		       
		        stompClient.setMessageConverter(new MappingJackson2MessageConverter());  
		        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();  
		        taskScheduler.afterPropertiesSet();  
		        stompClient.setTaskScheduler(taskScheduler); // for heartbeats  
		        Map<String,Object> request = Maps.newHashMap();
		        request.put("username", "admin");
		        request.put("rememberMe", true);
		        request.put("password",  "483922");
		        Map<String,Object> map = rest.postForObject("https://www.shanfupai.com/api/authenticate", request, Map.class);
		        String jwt = (String) map.get("id_token");
		       
		        String url = "wss://www.shanfupai.com/websocket/tracker?access_token="+jwt;  
		        System.err.println(url);
		        StompSessionHandler myHandler = new MyStompSessionHandler(latch);  
		        stompClient.connect(url, myHandler);  
		        try {  
//		            latch.await(3, TimeUnit.SECONDS);  
		        	 latch.await();  
		        }  
		        catch (InterruptedException e) {  
		            // TODO Auto-generated catch block  
		            e.printStackTrace();  
		        }  
	        
		 }
	

		
}












class MyStompSessionHandler extends StompSessionHandlerAdapter {  
    private CountDownLatch latch;  
  
    public MyStompSessionHandler(CountDownLatch latch) {  
        this.latch = latch;  
    }  
  
    @Override  
    public void afterConnected(StompSession session,  
            StompHeaders connectedHeaders) {  
         System.out.println("StompHeaders: " + connectedHeaders.toString());  
       
         
        session.subscribe("/topic/tracker", new StompFrameHandler() {  
            @Override  
            public Type getPayloadType(StompHeaders headers) {  
                return Object.class;  
            }  
  
            @Override  
            public void handleFrame(StompHeaders headers, Object payload) {  
                System.out.println(payload);  
                latch.countDown();  
                session.disconnect();  
            }  
        });  
        
        Map<String,String> data = Maps.newHashMap();
        data.put("page", "6666");
        session.send("/topic/activity", data);  
    }  
  
    @Override  
    public void handleException(StompSession session, StompCommand command,  
            StompHeaders headers, byte[] payload, Throwable exception) {  
        System.out.println(exception.getMessage());  
    }  
  
    @Override  
    public void handleTransportError(StompSession session,  
            Throwable exception) {  
    	exception.printStackTrace();
        System.out.println("transport error.");  
    }  
}  
